import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

export const takeawayStore = createSlice({
  name: 'takeway',
  initialState: {
    // 商品列表
    foodsList: [],
    activeIndex: 0,
    // 购物车列表
    cartList: []
  },
  reducers: {
    setFoodsList: (state, action) => {
      state.foodsList = action.payload
    },
    setActiveIndex: (state, action) => {
      state.activeIndex = action.payload
    },
    // 添加到购物车
    addCart: (state, action) => {
      // 是否添加过
      let item = state.cartList.find(item => item.id === action.payload.id)
      // 添加过，增加数量
      if (item) {
        item.count++
        console.log('state.cartList ', JSON.parse(JSON.stringify(state.cartList)))
      } else {
      // 没有添加过，添加
        state.cartList.push(action.payload)
        console.log('state.cartList ', JSON.parse(JSON.stringify(state.cartList)))
      }
    },
    // 增加计数
    increCount: (state, action) => {
      let item = state.cartList.find(item => item.id === action.payload.id)
      item.count++
    },
    // 减少计数
    decreCount: (state, action) => {
      let item = state.cartList.find(item => item.id === action.payload.id)
      if (item.count === 0) return
      item.count--
    },
    // 清空购物车
    clearCart: (state, action) => {
      state.cartList = []
    }
  }
})

// 异步获取数据
const fetchFoodsList = () => {
  return async (dispatch) => {
    const URL = 'http://localhost:3004/takeaway'
    const res = await axios.get(URL)
    // 调用 dispatch 函数提交 action
    dispatch(setFoodsList(res.data))
  } 
}

const { setFoodsList, setActiveIndex, addCart, increCount, decreCount, clearCart } = takeawayStore.actions
export { fetchFoodsList, setActiveIndex, setFoodsList, addCart, increCount, decreCount, clearCart }

const reducer = takeawayStore.reducer
export default reducer